<template>
  <div v-if="false" />
</template>

<script>
import { getProList } from '@/api/list'
import { saveList, getList } from '@/db/bufferList'
const { log } = console
export default {
  props: {
    type: {
      required: true,
      type: String
    }
  },
  data() {
    return {
      // 用来渲染的数据
      list: [],
      // 服务器端数据
      listServer: [],
      // 本地数据
      listClient: [],
      // 读取状态
      isDone: {
        isServerDone: false,
        isClientDone: false
      }
    }
  },
  watch: {
    list() {
      this.$emit('get-data', this.list)
    }
  },
  created() {
    // 获取本地数据
    this.fetchClientList()
    // 获取服务器数据
    this.fetchServerList()()
  },
  methods: {
    // 获取服务器数据
    fetchServerList(num = 0) {
      const miva = this
      return function handler() {
        log('num', num)
        if (num >= 3) return log('递归防御启动!')
        getProList(miva.type)
          .then(res => {
            log('获取服务器数据成功', res)
            miva.list = res.data.datalist
            miva.listServer = res.data.datalist
            miva.isDone.isServerDone = true
            miva.checkData()
          })
          .catch(err => {
            log('获取服务器数据失败, 3秒后重试', err)
            setTimeout(miva.fetchServerList(num + 1), 1000 * 3)
          })
      }
    },
    // 获取本地数据
    fetchClientList() {
      getList(this.type)
        .then(res => {
          log('获取本地数据成功', res)
          this.list = res.list
          this.listClient = res.list
          this.isDone.isClientDone = true
          this.checkData()
        })
        .catch(err => {
          log('本地无数据', err)
          this.isDone.isClientDone = true
          this.checkData()
        })
    },
    // 判断两端状态
    checkData() {
      for (const temp in this.isDone) {
        if (this.isDone[temp] === false) {
          return log('有一端还没获取完')
        }
      }
      this.saveClientList()
    },
    // 更新本地数据
    saveClientList() {
      saveList(this.type, this.listServer)
        .then(res => {
          this.list = this.listServer
          log('本地数据更新成功', res)
        })
        .catch(err => {
          log('本地数据更新失败', err)
        })
    }
  }
}
</script>
